#!/bin/bash

set -e

if [[ -n "${CI}" ]]; then 
	REGISTRY_USER=gitlab-ci-token
#	REGISTRY_PASSWORD=${CI_JOB_TOKEN}
	REGISTRY_URL=${CI_REGISTRY}
	DOCKER_PROJECT=${CI_PROJECT_PATH}
	REGISTRY_IMAGE=${DOCKER_IMAGE#*/}
	[[ "${CI_PROJECT_PATH#*/}" == "${REGISTRY_IMAGE%:*}" ]] && DOCKER_PROJECT=${CI_PROJECT_PATH%/*}
elif [[ -f .env ]]; then
	source ${BASH_SOURCE[0]%/*}/.env
	CI_JOB_TOKEN=${REGISTRY_PASSWORD}
fi	

echo DOCKER_IMAGE=${DOCKER_IMAGE}
echo DOCKER_PROJECT=${DOCKER_PROJECT}

docker login -u ${REGISTRY_USER} -p ${CI_JOB_TOKEN} ${REGISTRY_URL}

docker tag ${DOCKER_IMAGE} ${REGISTRY_URL}/${DOCKER_PROJECT}/${REGISTRY_IMAGE}
docker push ${REGISTRY_URL}/${DOCKER_PROJECT}/${REGISTRY_IMAGE}

if [[ -n "${DOCKER_TAG_AS_LATEST}" ]]; then
    REGISTRY_IMAGE=${REGISTRY_IMAGE%:*}:latest
    docker tag ${DOCKER_IMAGE} ${REGISTRY_URL}/${DOCKER_PROJECT}/${REGISTRY_IMAGE}
    docker push ${REGISTRY_URL}/${DOCKER_PROJECT}/${REGISTRY_IMAGE}
fi